package at.com.vn.chess.applet;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JApplet;

import vn.com.bip.office.smart.util.XMLHelper;

import at.com.vn.chess.entity.ChatUser;
import at.com.vn.chess.network.ClientUtil;
import at.com.vn.chess.util.Const;

public class CloseBrowserApplet extends JApplet implements ActionListener,
		Runnable {
	private static final long serialVersionUID = 2896461443956041091L;
	private String url_servlet_base = Const.URL_CHESS_APPLICATION;
	private String url_servlet_chat = url_servlet_base + "/ChatPublicServlet";
	private String name = "Mr X";

	private ClientUtil clientUtil;

	String xmlMsg;

	// Threads
	private Thread thread;

	public void init() {

		// Get parameter from web
		url_servlet_base = this.getParameter(Const.WEB_PARAM_SERVER_URL_BASE);
		name = this.getParameter(Const.WEB_PARAM_USER_ID);

		if (url_servlet_base == null || url_servlet_base.equals("")) {
			// static final String URL_SERVLET =
			// "http://172.25.100.206:8080/ChessApplication/ChatPublicServlet";
			url_servlet_base = Const.URL_CHESS_APPLICATION;
			url_servlet_chat = url_servlet_base + "/ChatPublicServlet";
		}
		if (name == null) {
			name = "";
		}
		clientUtil = new ClientUtil(getCodeBase(), url_servlet_chat, name, "");
	}

	@Override
	public void start() {
		thread = new Thread(this);
		thread.start();
	}

	@Override
	public void destroy() {

		if (name == null || name.equals("")) {
			return;
		}
		// When user left, remove out of list, show all client
		xmlMsg = prepareChatMsg(Const.PROCESS_CHAT_PUBLIC_LEFT, " has left...");
		clientUtil.sendBroadcastMessage(xmlMsg);
	}

	@Override
	public void run() {
		Thread thisThread = Thread.currentThread();
		while (thread == thisThread) {
			try {
				Thread.sleep(Const.ONE_SECOND);
			} catch (InterruptedException e) {
			}
		}

	}

	private String prepareChatMsg(String propName, String message) {
		ChatUser user = new ChatUser();
		user.setUserID(name);
		user.setChatMsg(message);
		user.setIsActive(1);
		return XMLHelper.convertListObjectToXML(user, propName, ChatUser.class);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub

	}
}